#include <QPushButton>
#include <QTextEdit>
#include <QProcess>

#include "configwidget.h"

QString ConfigWidget::getSetting(QString key) {
    return settings->value(key, defaultKV[key]).toString();
}

ConfigWidget::ConfigWidget(QWidget *parent)
    : QWidget(parent), settings(new QSettings("FusionPilot", "ConfigWidget", this))
{
    // 设置垂直布局
    layout = new QVBoxLayout(this);

    auto title = new QLabel("Fusion Pilot 配置界面",this);
    title->setStyleSheet("font-size: 40px;");
    layout->addWidget(title, 0, Qt::AlignHCenter);
    layout->addStretch();

    // aiderApiTypeBox = new QComboBox(this);
    // aiderApiTypeBox->addItems(aiderApiTypes);
    // aiderApiTypeBox->setItemData(getSetting("aider_api_type"));

    // 创建配置项
    createConfigItem("语法树选择模块的Python可执行文件路径", "tss_python_bin_path");
    createConfigItem("AI模块的Python可执行文件路径", "aider_python_bin_path");
    createConfigItem("设置aider的API类型", "aider_api_type");
    createConfigItem("设置aider的API key", "aider_api_key");
    createPythonTestWidget();
    createRgTestWidget();
    layout->addStretch();

    setLayout(layout);
}

ConfigWidget::~ConfigWidget()
{
    delete settings;
}

void ConfigWidget::createPythonTestWidget() {
    QHBoxLayout *hlayout = new QHBoxLayout;
    QFrame *frame = new QFrame;
    hlayout->addSpacerItem(new QSpacerItem(40, 0, QSizePolicy::Fixed));
    
    // 标签
    QLabel *label = new QLabel("测试 Python 环境，请注意 tree-sitter 和 aider 是否正确安装：", frame);
    hlayout->addWidget(label);
    QPushButton *button = new QPushButton("开始测试");
    hlayout->addWidget(button);

    hlayout->addSpacerItem(new QSpacerItem(40, 0, QSizePolicy::Fixed));
    hlayout->setAlignment(Qt::AlignCenter);
    frame->setLayout(hlayout);

    layout->addWidget(frame);

    QHBoxLayout *hTElayout = new QHBoxLayout;
    QFrame *vframe = new QFrame;
    vframe->setLayout(hTElayout);
    QTextEdit *tssOutput = new QTextEdit;
    QTextEdit *aiderOutput = new QTextEdit;
    tssOutput->setReadOnly(true);
    aiderOutput->setReadOnly(true);
    hTElayout->addSpacerItem(new QSpacerItem(40, 0, QSizePolicy::Fixed));
    hTElayout->addWidget(tssOutput);
    hTElayout->addWidget(aiderOutput);
    hTElayout->addSpacerItem(new QSpacerItem(40, 0, QSizePolicy::Fixed));
    layout->addWidget(vframe);

    connect(button, &QPushButton::clicked, [tssOutput, aiderOutput, this]() {
        QString tssPyPath = getSetting("tss_python_bin_path");
        QString aiderPyPath = getSetting("aider_python_bin_path");
        QProcess process;

        process.start("sh", QStringList() << "-c" << tssPyPath + " -m pip freeze | grep -e tree-sitter");
        process.waitForFinished();
        QString output = process.readAllStandardOutput();
        QString errOutput = process.readAllStandardError();
        tssOutput->setText("tree-sitter 环境测试：\n");
        if (!errOutput.isEmpty()) {
            tssOutput->append(errOutput);
            tssOutput->setStyleSheet("color: #c0392b;");
        } else {
            tssOutput->append(output);
            tssOutput->setStyleSheet("color: #11d116;");
        }

        process.start("sh", QStringList() << "-c" << aiderPyPath + " -m pip freeze | grep -e aider");
        process.waitForFinished();
        output = process.readAllStandardOutput();
        errOutput = process.readAllStandardError();
        aiderOutput->setText("aider-chat 环境测试：\n");
        if (!errOutput.isEmpty()) {
            aiderOutput->append(errOutput);
            aiderOutput->setStyleSheet("color: #c0392b;");
        } else {
            aiderOutput->append(output);
            aiderOutput->setStyleSheet("color: #11d116;");
        }
    });
}

void ConfigWidget::createRgTestWidget() {
    QHBoxLayout *hlayout = new QHBoxLayout;
    QFrame *frame = new QFrame;
    hlayout->addSpacerItem(new QSpacerItem(40, 0, QSizePolicy::Fixed));
    
    // 标签
    QLabel *label = new QLabel("测试 Rg 命令，如果有版本号显示则一切正常：", frame);
    hlayout->addWidget(label);
    QPushButton *button = new QPushButton("开始测试");
    hlayout->addWidget(button);

    hlayout->addSpacerItem(new QSpacerItem(40, 0, QSizePolicy::Fixed));
    hlayout->setAlignment(Qt::AlignCenter);
    frame->setLayout(hlayout);

    layout->addWidget(frame);

    QTextEdit *textEdit = new QTextEdit;
    textEdit->setReadOnly(true);
    layout->addWidget(textEdit);

    connect(button, &QPushButton::clicked, [textEdit]() {
        QProcess process;
        process.start("rg", QStringList() << "--version");
        process.waitForFinished();
        QString output = process.readAllStandardOutput();
        QString errOutput = process.readAllStandardError();
        if (!errOutput.isEmpty()) {
            textEdit->setText(errOutput);
            textEdit->setStyleSheet("color: #c0392b;");
        } else {
            textEdit->setText(output);
            textEdit->setStyleSheet("color: white;");
        }
    });
}

// 创建一个配置项
void ConfigWidget::createConfigItem(const QString &description, const QString &key, QWidget *settingWidget)
{
    QHBoxLayout *hlayout = new QHBoxLayout;
    QFrame *frame = new QFrame;
    hlayout->addSpacerItem(new QSpacerItem(40, 0, QSizePolicy::Fixed));
    
    // 标签
    QLabel *label = new QLabel(description + ": ", frame);
    hlayout->addWidget(label);

    if (settingWidget == nullptr) {
        // 输入框
        QLineEdit *lineEdit = new QLineEdit(frame);
        hlayout->addWidget(lineEdit);
        // 从 QSettings 加载已保存的值
        lineEdit->setText(getSetting(key));
        // 当输入框的值改变时保存到 QSettings
        connect(lineEdit, &QLineEdit::textChanged, this, [=](const QString &value) {
            onValueChanged(key, value);
        });
    } else {
        hlayout->addWidget(settingWidget);
    }

    hlayout->addSpacerItem(new QSpacerItem(40, 0, QSizePolicy::Fixed));
    hlayout->setAlignment(Qt::AlignCenter);
    frame->setLayout(hlayout);

    layout->addWidget(frame);
}

// 保存值到 QSettings
void ConfigWidget::onValueChanged(const QString &key, const QString &value)
{
    settings->setValue(key, value);
}
